package by.dkusch.aircompany.services.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.metamodel.SingularAttribute;

import org.apache.commons.lang3.Validate;

import by.dkusch.aircompany.dao.AbstractDao;
import by.dkusch.aircompany.model.tables.base.BaseEntity;
import by.dkusch.aircompany.services.AbstractService;

/**
 * Abstract service class
 **/
public abstract class AbstractServiceImpl<ID, Entity extends BaseEntity<ID>> implements AbstractService<ID, Entity> {

	/**
	 * Abstract dao for service - injected by a spring configuration
	 **/
	AbstractDao<ID, Entity> dao;

	public AbstractDao<ID, Entity> getDao() {
		return dao;
	}

	public void setDao(AbstractDao<ID, Entity> dao) {
		this.dao = dao;
	}

	@Override
	public Entity get(ID id) {
		Entity entity = dao.getById(id);
		return entity;
	}

	@Override
	public void saveOrUpdate(Entity ent) {
		/*
		 * DateTime of correction
		 */
		ent.setCorrectDt(new Date(System.currentTimeMillis()));
		/* TODO write current web user id */
		if (ent.getId() == null) {
			/**
			 * set arcFl as false for a new record when saving
			 **/
			ent.setArcFl(false);
			dao.insert(ent);
		} else {
			dao.update(ent);
		}
	}

	@Override
	public void delete(Entity ent) {
		dao.delete(ent.getId());
	}

	@Override
	public void deleteAll() {
		dao.deleteAll();
	}

	@Override
	public void changeArchiveFL(boolean arcFL, Entity ent) {
		Validate.isTrue(ent.getId() != null, "This method should be called for saved entities only!");
		ent.setArcFl(arcFL);
		saveOrUpdate(ent);
	}

	@Override
	public void saveList(List<Entity> records) {
		dao.saveList(records);
	}

	public List<Entity> getAllByFieldRestriction(
			final SingularAttribute<? super Entity, ?> attribute, final Object value) {
		return dao.getAllByFieldRestriction(attribute, value);
	}
}
